<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:task:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:task:export']">导出</el-button> -->
      </el-col>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
        class="el-form-search">
        <el-form-item label="任务名称" prop="name" class="el-form-search-item">
          <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="连接名称" prop="connName" class="el-form-search-item">
          <el-input v-model="queryParams.connName" placeholder="请输入连接名称" clearable size="mini"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" width="80" />
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="连接名称" align="center" prop="connName" />
      <el-table-column label="导出格式" align="center" prop="format" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="最大保留份数" align="center" prop="maxNum" />

      <el-table-column label="自动转存" align="center" prop="transToConnList" width="200" >
        <template slot-scope="scope">
        <el-tag style="margin-bottom:5px" v-for="(item, index) in scope.row.transToConnListArr" :key="index" type="success">{{item}}</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="失败邮件通知" align="center" prop="emails" width="200" >
        <template slot-scope="scope">
        <el-tag style="margin-bottom:5px" v-for="(item, index) in scope.row.emailsArr" :key="index" type="success">{{item}}</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleRun(scope.row)">执行一次</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改数据库备份任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false"
      v-dialogDrag>
      <div style="max-height: 450px;overflow-y: auto;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="任务名称" prop="name">
            <el-input :disabled="title == '修改数据库备份任务'" v-model="form.name" placeholder="请输入任务名称" />
          </el-form-item>

          <!-- 选择连接名称 -->
          <el-form-item label="连接名称" prop="connName">
            <el-select :disabled="title == '修改数据库备份任务'" style="width: 100%;" v-model="form.connName" placeholder="请选择连接名称"
              @change="connChange">
              <el-option v-for="item in connList" :key="item.id" :label="item.connName"
                :value="item.connName"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="导出格式" prop="format">
            <!-- 下拉选项 -->
            <el-select v-model="form.format" placeholder="请选择导出格式" style="width: 100%;">
              <el-option label="csv" value="csv"></el-option>
              <el-option label="sql" value="sql"></el-option>
            </el-select>
          </el-form-item>


          <!-- 额外参数 -->
          <el-form-item label="额外参数" prop="extraParams" v-if="form.format == 'sql'">
            <!-- 多选框 -->
            <el-checkbox-group v-model="extraParams" @change="extraParamsChange">
              <div class="paramstyle">
                <el-checkbox size="mini" label="a">在 CREATE TABLE 之前添加 DROP TABLE</el-checkbox>
                <el-checkbox size="mini" label="b">在每个 INSERT 中包含列名</el-checkbox>
              </div>
              <div class="paramstyle">
                <el-checkbox size="mini" label="c">在每个 INSERT 前添加 DISABLE KEYS</el-checkbox>
                <el-checkbox size="mini" label="d">在 CREATE TABLE 中包含所有表选项</el-checkbox>
              </div>
              <div class="paramstyle">
                <el-checkbox size="mini" label="e">在每次表转储之前添加 LOCK TABLES</el-checkbox>
                <el-checkbox size="mini" label="f">在转储中包含存储的例程</el-checkbox>
              </div>
              <div class="paramstyle">
                <el-checkbox size="mini" label="g">在 CREATE TRIGGER 之前添加 DROP TRIGGER</el-checkbox>
                <el-checkbox size="mini" label="h">在导出期间锁定所有表</el-checkbox>
              </div>

              <div class="paramstyle">
                <el-checkbox size="mini" label="i">导出不带数据的架构</el-checkbox>
                <el-checkbox size="mini" label="j">使用 INSERT DELAYED (最高为 MySQL 5.5)</el-checkbox>
              </div>

              <div class="paramstyle">
                <el-checkbox size="mini" label="k">导出不带表空间的架构</el-checkbox>
                <el-checkbox size="mini" label="l">对多行使用单个 INSERT</el-checkbox>
              </div>

              <div class="paramstyle">
                <el-checkbox size="mini" label="m">导出而不创建表</el-checkbox>
                <el-checkbox size="mini" label="n">使用 QUICK 选项</el-checkbox>
              </div>
            </el-checkbox-group>
          </el-form-item>


          <el-form-item label="" v-if="form.connName != null">
            <!-- 添加搜索功能 -->
            <el-input v-model="tableSearch" placeholder="请输入表名称" clearable @keyup.enter.native="searchRecoveryTable"
              style="width: 200px;"></el-input>
            <el-button style="margin-left:10px" type="primary" @click="searchRecoveryTable">搜索</el-button>
            <div style="margin-top: 10px;">
            </div>
          </el-form-item>

          <el-alert title="表列表包含了视图，如果只备份视图，恢复时，请保证对应表存在！" :closable="false" type="success"/>
          <el-form-item label="表列表" prop="tables" v-if="form.connName != null">
            <!-- 表格显示表列表 添加多选 -->
            <el-table ref="table" :height="200" :data="tables" border :row-key="(row) => row.tableName"
              style="width: 100%;" @selection-change="tableSelectChange">
              <el-table-column type="selection" width="100" align="center" />
              <el-table-column prop="tableName" label="表名称" align="center"></el-table-column>
              <el-table-column prop="tableType" label="表类型" align="center"></el-table-column>
            </el-table>
          </el-form-item>


          <el-form-item label="cron表达式" prop="cronExpression">
            <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式">
              <template slot="append">
                <el-button type="primary" @click="handleShowCron">
                  生成表达式
                  <i class="el-icon-time el-icon--right"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="最大保留份数" prop="format">
            <!-- 下拉选项 -->
            <el-input-number :min="1" v-model="form.maxNum" placeholder="请输入最大保留份数" style="width: 100%;">
            </el-input-number>
          </el-form-item>

          <!-- 状态 -->
          <el-form-item label="开启" prop="status">
            <el-switch v-model="form.status" active-value="0" inactive-value="1"></el-switch>
          </el-form-item>



          <!-- 开启自动转存 -->
          <el-alert title="当备份成功后，自动将备份数据转存指定数据库,当前功能可以用来实现T+1的数据迁移" :closable="false" type="success">
          </el-alert>
          <el-form-item style="margin-top:10px" label="自动转存数据" prop="status">
            <el-select style="width: 100%;" v-model="form.transToConnListArr" multiple placeholder="请选择" :disabled="form.connName == null" @change="transToConnListChange">
              <el-option v-for="item in connList" :key="item.id" :label="item.connName" 
              :disabled="item.connName==form.connName"
                :value="item.connName"></el-option>
            </el-select>
          </el-form-item>


          <!--  -->
          <el-form-item style="margin-top:10px" label="失败邮件通知" prop="status">
            <el-select style="width: 100%;" v-model="form.emailsArr" filterable multiple placeholder="请选择"  @change="emailListChange">
              <el-option v-for="item in mailUserList" :key="item" :label="item" 
                :value="item"></el-option>
            </el-select>
            </el-form-item>



        </el-form>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron = false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>



  </div>
</template>
  
<script>
import { listTask, getTask, delTask, addTask, updateTask,mailList } from "@/api/db/task";
import { listConn, getTableList } from "@/api/db/conn";
import Crontab from '@/components/Crontab'
import {
  delJob,
  addJob1,
  editBackupJob,
  runJob
} from "@/api/monitor/job";


export default {
  name: "Task",
  components: {
    Crontab
  },
  data() {

    let c = ['a', 'c', 'd', 'e', 'h', 'l'];
    return {
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库备份任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "id",
        isAsc: "desc",
        name: null,
        connName: null,
        format: null,
        tables: null,
        qrtzJobId: null,
      },
      // 表单参数
      form: {
        extraParamsH5: null,
      },
      // 表单校验
      rules: {
        tables: [
          { required: true, message: "导出的表名称，以,作为分隔符号不能为空", trigger: "blur" }
        ],
        cronExpression: [
          { required: true, message: "cron表达式不能为空", trigger: "blur" }
        ],
        format: [
          { required: true, message: "导出格式不能为空", trigger: "blur" }
        ],
        maxNum: [
          { required: true, message: "最大保留份数不能为空", trigger: "blur" }
        ]
      },
      tables: [],
      expression: "",
      openCron: false,
      jobids: [],
      tableSearch: '',

      extraParams: c,

      connList: [],

      // 查询参数
      mailUserList:[],
    };
  },
  created() {
    this.getList();
  },
  methods: {

    getMailUserList(){
      mailList({}).then(response => {
       this.mailUserList= response.data; 
      })

    },
    emailListChange(val){
      this.form.emails = val.join(",");
    },

    transToConnListChange(val){
      this.form.transToConnList = val.join("#");
    },


    extraParamsChange(val) {
      let list = val.join("#");
      this.form.extraParamsH5 = list;
      console.log(this.form.extraParamsH5);
    },

    searchRecoveryTable() {
      this.connChange(this.form.connName);
    },
    /* 立即执行一次 */
    handleRun(row) {
      this.$modal
        .confirm('确认要立即执行一次"' + row.name + '"任务吗？')
        .then(function () {
          return runJob(row.qrtzJobId, row.jobGroup);
        })
        .then(() => {
          this.$modal.msgSuccess("执行成功");
        })
        .catch(() => { });
    },

    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      let that = this;
      this.$modal
        .confirm('确认要"' + text + '""' + row.name + '"任务吗？')
        .then(function () {
          return that.updateInfo(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cronExpression = value;
    },

    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cronExpression;
      this.openCron = true;
    },

    connChange(name) {
      return getTableList({ connName: name, tableName: this.tableSearch, }).then(response => {
        let c = response.data;
        let tables = c.map(item => {
          return {
            tableName: item.TABLE_NAME,
            tableType: item.TABLE_TYPE
          }
        });
        this.tables = tables;
        this.$refs.table.clearSelection();
      });
    },


    handleDetail() {

    },

    /** 查询数据库备份任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        response.rows.forEach(item => {
          if(item.transToConnList!=null){
           item.transToConnListArr = item.transToConnList.split("#"); 
          }
          if(item.emails!=null){
            item.emailsArr=item.emails.split(",");
          }
        })
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      //查询所有的连接
      listConn({}).then(response => {
        this.connList = response.rows;
      })

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        connName: null,
        format: null,
        tables: null,
        qrtzJobId: null,
        id: null,
        maxNum: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.jobids = selection.map(item => item.qrtzJobId)
    },

    tableSelectChange(selection) {
      this.form.tables = selection.map(item => item.tableName).join("#");
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库备份任务";
      this.tables = [];

      this.getMailUserList();

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      this.getMailUserList();

      const id = row.id || this.ids
      return getTask(id).then(response => {
        // response.data.extraParamsH5=response.data.extraParamsH5.split(",");
        if(response.data.transToConnList!=null){
          response.data.transToConnListArr = response.data.transToConnList.split("#");
        }
        if(response.data.emails!=null){
          response.data.emailsArr = response.data.emails.split("#");
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改数据库备份任务";
        this.$forceUpdate();
        this.extraParams = this.form.extraParamsH5.split("#");

        this.connChange(this.form.connName).then(() => {
          this.$nextTick(() => {
            if (this.$refs.table && this.form.tables) {
              let tables = this.form.tables.split("#");
              this.tables.forEach(row1 => {
                if (tables.indexOf(row1.tableName) > -1) {
                  this.$refs.table.toggleRowSelection(row1, true);
                }
              });
            }
          });
        })
      });
    },

    updateInfo(form, modify) {
      console.log("传递参数", form)
      let job = {
        cronExpression: form.cronExpression,
        jobId: form.qrtzJobId,
        status: form.status,
        remark: this.form.id
      }
      editBackupJob(job).then(response => {
        updateTask(form).then(response => {
          if (modify) {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
          }
          this.getList();
        });
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {

        //判断格式==sql
        if (this.form.format == "sql") {
          if (this.form.extraParamsH5 == null) {
            this.form.extraParamsH5 = this.extraParams.join("#");
          }
        }
        if (valid) {
          if (this.form.id != null) {

            //先修改job任务，然后修改数据库备份任务
            this.updateInfo(this.form, true);

          } else {


            //先添加到job任务中，然后添加到数据库备份任务中
            let job = {
              jobName: this.form.name,
              jobGroup: "DEFAULT",
              cronExpression: this.form.cronExpression,
              status: this.form.status,
              remark: this.form.id
            }
            addJob1(job).then((response) => {
              let qrtzJobId = response.data;
              this.form.qrtzJobId = qrtzJobId;
              addTask(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const jobids = row.qrtzJobId || this.jobids;
      this.$modal.confirm('是否确认删除记录？').then(function () {
        return delJob(jobids).then(response => {
          delTask(ids);
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('db/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
  
<style lang="css">
.paramstyle {
  height: 25px;
}
</style>